<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <!-- 登录的表单 -->
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="loginForms"
        >
          <h1>Hello</h1>
          <h2>基于BP二手房房价预测与分析</h2>
          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              v-model="loginForm.username"
              placeholder="请输入账号"
              style="height: 50px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="new_password">
            <el-input
              type="password"
              :prefix-icon="Lock"
              v-model="loginForm.new_password"
              show-password
              placeholder="请输入密码"
              style="height: 50px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <div style="display: flex; align-items: center">
              <!-- el-input 在左边 -->
              <el-input
                v-model="loginForm.captcha"
                placeholder="请输入验证码"
                :prefix-icon="Lock"
                style="
                  width: 300px !important;
                  height: 50px;
                  flex: 1;
                  margin-right: 10px;
                "
              />

              <!-- el-image 在右边，显示验证码图片 -->
              <el-image
                :src="captchaImageUrl"
                fit="contain"
                style="width: 150px; height: 50px; cursor: pointer"
                alt="验证码图像"
                @click="refreshCaptcha"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loading"
              class="login_btn"
              type="primary"
              size="default"
              @click="forget"
            >
              忘记密码
            </el-button>
          </el-form-item>
          <el-form-item>
            <div class="link-item">
              <div class="link">
                <RouterLink to="/login">
                  <el-link>有账号？去登录</el-link>
                </RouterLink>
              </div>
              <div class="link">
                <RouterLink to="/register">
                  <el-link style="margin-left: 60%">无账号？去注册</el-link>
                </RouterLink>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, defineComponent, onMounted } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
// 只提供局部引用的方式，不再采用插件形式，方便按需加载，减少主包大小
import SlideVerify, { SlideVerifyInstance } from 'vue3-slide-verify'
import 'vue3-slide-verify/dist/style.css'
// 引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
// 引入路由
import { useRouter, useRoute, RouterLink } from 'vue-router'
import { ElNotification } from 'element-plus'
//引入获取当前时间的函数
import { getTime } from '@/utils/time'
// 获取验证码接口
import { reqCaptchaAPI, reqForget } from '@/api/user/index'

let useStore = useUserStore()
// 获取路由对象
let router = useRouter()
// 使用路由参数，使得点击登录后跳转到对应的路由
let route = useRoute()
//定义变量控制按钮加载效果
let loading = ref(false)
//获取el-form组件
let loginForms = ref()
//收集账号与密码的数据
let loginForm = reactive({ username: '', password: '', captcha: '' })
// 验证码图片链接
const captchaImageUrl = ref<string>('')

onMounted(() => {
  reqCaptcha()
})
// 请求验证码
const reqCaptcha = async () => {
  try {
    const response = await reqCaptchaAPI()
    // 尝试直接获取 blob
    const blob = response // 如果响应就是 blob 类型
    if (blob instanceof Blob) {
      const url = URL.createObjectURL(blob)
      captchaImageUrl.value = url
    } else {
      throw new Error('返回的数据不是 Blob 类型')
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  reqCaptcha()
}
// 忘记密码
const forget = async () => {
  let res: any = await reqForget(loginForm)
  if (res.code === 200) {
    ElNotification({
      type: 'success',
      message: res.msg,
    })
    //登录成功加载效果也消失
    loading.value = false
    router.push('/login')
  } else {
    ElNotification({
      type: 'error',
      message: res.error_msg,
    })
  }
}

//自定义校验规则函数
const validatorUserName = (rule: any, value: any, callback: any) => {
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  if (value.length >= 6 && value.length <= 18) {
    callback()
  } else {
    callback(new Error('账号长度为6-18位之间'))
  }
}

const validatorPassword = (rule: any, value: any, callback: any) => {
  let regExp = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z0-9]{6,18}$/
  if (regExp.test(value)) {
    callback()
  } else {
    callback(new Error('密码必须包含至少1个字母和1个数字，且长度为6-18位'))
  }
}
const validatorCaptcha = (rule: any, value: any, callback: any) => {
  // rule: 即为校验规则对象
  // value: 即为表单元素文本内容
  // callback: 校验完成后调用的回调函数

  let regExp = /^\d{6}$/ // 正则表达式确保是6位数字
  if (regExp.test(value)) {
    callback() // 校验通过
  } else {
    callback(new Error('账号长度必须为6位的数字')) // 校验失败
  }
}

//定义表单校验需要配置对象
const rules = {
  //规则对象属性:
  //required,代表这个字段务必要校验的
  //min:文本长度至少多少位
  //max:文本长度最多多少位
  //message:错误的提示信息
  //trigger:触发校验表单的时机 change->文本发生变化触发校验,blur:失去焦点的时候触发校验规则
  username: [
    // { required: true, min: 6, max: 10, message: '账号长度至少六位', trigger: 'change' }
    { trigger: 'change', validator: validatorUserName },
  ],
  password: [
    // { required: true, min: 6, max: 15, message: '密码长度至少6位', trigger: 'change' }
    { trigger: 'change', validator: validatorPassword },
  ],
  captcha: [{ trigger: 'change', validator: validatorCaptcha }],
}
</script>
<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/bg.jpg') no-repeat;
  background-size: cover;
  position: relative;

  .cover {
    width: fit-content;
    background-color: aliceblue;
    position: absolute;
    top: 110%;
    right: 27%;
    transform: translate(-50%, -50%);
    z-index: 1000;
  }

  .login_form {
    position: relative;
    top: 50%;
    right: 40%;
    width: 80%;
    // background: url('@/assets/images/login_form.png') no-repeat;
    // background-size: cover;
    background: rgba(243, 239, 239, 0.2);
    // background-color: rgba(232, 224, 224, 0.2);
    padding: 40px;
    h1 {
      color: #fff;
      font-size: 40px;
    }

    h2 {
      font-size: 20px;
      color: #fff;
      margin: 20px 0px;
    }
    .link-item {
      display: flex;
      justify-content: space-between;
      width: 100%;
      .link {
        flex: 1;
        font-size: 15px;
        .el-link {
          color: #fff;
        }
      }
      .link:hover {
        color: #0c24da;
      }
    }
    .login_btn {
      width: 100%;
    }
  }
}
</style>
